﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Media;
using Caliburn.Core.InversionOfControl;
using Caliburn.PresentationFramework;
using Caliburn.PresentationFramework.Invocation;
using MTGenome.MTG;
using MTGenome.UI;

namespace MTGenome.ViewModels
{
    public sealed class CardInlineViewModel : PropertyChangedBase, IText
    {
        private bool _isImage = false;
        private string _text = null;
        private ImageSource _image = null;

        public CardInlineViewModel(string text, bool isImage)
        {
            _isImage = isImage;
            if (_isImage)
            {
                _text = text + "]";

                Execute.OnBackgroundThread(() =>
                {
                    try
                    {
                        string path = IoC.Get<IGathererServer>().GetImagePath(text.TrimStart('['), ImageSize.Small);
                        if (string.IsNullOrEmpty(path))
                        {
                            Text = text;
                            IsImage = false;
                            return;
                        }

                        _image = ImageLoader.Load(path);
                        NotifyOfPropertyChange(() => Image);
                    }
                    catch
                    {
                        Text = text;
                        IsImage = false;
                    }
                });
            }
            else
            {
                _text = text.TrimEnd('\r', '\n');
            }
        }

        public bool IsText
        {
            get { return !_isImage; }
        }

        public bool IsImage
        {
            get { return _isImage; }
            private set { _isImage = value; NotifyOfPropertyChange(() => IsImage); NotifyOfPropertyChange(() => IsText); }
        }

        public ImageSource Image
        {
            get { return _image; }
        }

        public string Text
        {
            get { return _text; }
            private set { _text = value; NotifyOfPropertyChange(() => Text); }
        }

        public override string ToString()
        {
            return _text;
        }
    }
}
